<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <!--
        <el-form-item prop="system" label="系统">
          <el-input v-model="listQuery.system" placeholder="系统" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="systemName" label="系统名称">
          <el-input v-model="listQuery.systemName" placeholder="系统名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="service" label="服务">
          <el-input v-model="listQuery.service" placeholder="服务" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="serviceName" label="服务名">
          <el-input v-model="listQuery.serviceName" placeholder="服务名" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="model" label="模块">
          <el-input v-model="listQuery.model" placeholder="模块" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="prefix" label="前缀">
          <el-input v-model="listQuery.prefix" placeholder="前缀" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="sequenceNo" label="生成单号">
          <el-input v-model="listQuery.sequenceNo" placeholder="生成单号" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="sequenceIncrement" label="生成递增序列">
          <el-input v-model="listQuery.sequenceIncrement" placeholder="生成递增序列" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item label="生成时间">
          <el-date-picker v-model="listQuery.sequenceTimeRange"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="width: 380px"
                          type="datetimerange"
                          range-separator="-"
                          start-placeholder="生成时间开始"
                          end-placeholder="生成时间结束" />
        </el-form-item>
        <el-form-item prop="sequenceUser" label="生成操作用户">
          <User v-model="listQuery.sequenceUser" keyName="id" keyShow="name" placeholder="生成操作用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              style="width: 100%;"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="系统" prop="system" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.system }}</template>
      </el-table-column>
      <el-table-column align="center" label="系统名称" prop="systemName" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.systemName }}</template>
      </el-table-column>
      <el-table-column align="center" label="服务" prop="service" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.service }}</template>
      </el-table-column>
      <el-table-column align="center" label="服务名" prop="serviceName" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.serviceName }}</template>
      </el-table-column>
      <el-table-column align="center" label="模块" prop="model" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.model }}</template>
      </el-table-column>
      <el-table-column align="center" label="前缀" prop="prefix" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.prefix }}</template>
      </el-table-column>
      <el-table-column align="center" label="生成单号" prop="sequenceNo" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.sequenceNo }}</template>
      </el-table-column>
      <el-table-column align="center" label="生成递增序列" prop="sequenceIncrement" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.sequenceIncrement }}</template>
      </el-table-column>
      <el-table-column align="center" label="生成时间" prop="sequenceTime" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.sequenceTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="生成操作用户ID" prop="sequenceUser" min-width="205px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreign-ids="row.sequenceUser" :foreign-label="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button v-show="checkAuthByCode('')" type="danger" link @click="handleDelete(row)">删除</el-button>
          -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="系统" prop="system">
          <el-input v-model="obj.system" placeholder="请输入系统，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="obj.systemName" placeholder="请输入系统名称，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="服务" prop="service">
          <el-input v-model="obj.service" placeholder="请输入服务，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="服务名" prop="serviceName">
          <el-input v-model="obj.serviceName" placeholder="请输入服务名，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="模块" prop="model">
          <el-input v-model="obj.model" placeholder="请输入模块，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="前缀" prop="prefix">
          <el-input v-model="obj.prefix" placeholder="请输入前缀，最多输入10个字符" />
        </el-form-item>
        <el-form-item label="生成单号" prop="sequenceNo">
          <el-input v-model="obj.sequenceNo" placeholder="请输入生成单号，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="生成递增序列" prop="sequenceIncrement">
          <el-input v-model="obj.sequenceIncrement" type="number" placeholder="请输入生成递增序列" />
        </el-form-item>
        <el-form-item label="生成时间" prop="sequenceTime">
          <el-date-picker v-model="obj.sequenceTime" placeholder="请输入生成时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="生成操作用户ID" prop="sequenceUser">
          <el-input v-model="obj.sequenceUser" type="number" placeholder="请输入生成操作用户ID" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import baseConfig from '@/mixins/baseConfig'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess} from "@/config/common";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  system: 'icims', // 系统
  systemName: '内控信息管理', // 系统名称
  service: 'icims-api', // 服务
  serviceName: '接口服务', // 服务名
  model: null, // 模块
  prefix: null, // 前缀
  sequenceNo: null, // 生成单号
  sequenceIncrement: null, // 生成递增序列
  sequenceTime: null, // 生成时间
  sequenceUser: null, // 生成操作用户ID
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'sequence_nocache',
  components: {User},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        system: null,
        systemName: null,
        service: null,
        serviceName: null,
        model: null,
        prefix: null,
        sequenceNo: null,
        sequenceIncrement: null,
        sequenceTimeStart: null,
        sequenceTimeEnd: null,
        sequenceUser: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
        sequenceTimeRange: [], //
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        system: [{ required: false, validator: customValidator, min: 0, max: 100, label: '系统', trigger: ['blur', 'change'] }],
        systemName: [{ required: false, validator: customValidator, min: 0, max: 100, label: '系统名称', trigger: ['blur', 'change'] }],
        service: [{ required: false, validator: customValidator, min: 0, max: 100, label: '服务', trigger: ['blur', 'change'] }],
        serviceName: [{ required: false, validator: customValidator, min: 0, max: 200, label: '服务名', trigger: ['blur', 'change'] }],
        model: [{ required: false, validator: customValidator, min: 0, max: 100, label: '模块', trigger: ['blur', 'change'] }],
        prefix: [{ required: false, validator: customValidator, min: 0, max: 10, label: '前缀', trigger: ['blur', 'change'] }],
        sequenceNo: [{ required: false, validator: customValidator, min: 0, max: 200, label: '生成单号', trigger: ['blur', 'change'] }],
        sequenceIncrement: [{ required: false, validator: customValidator, min: 0, max: 20, label: '生成递增序列', trigger: ['blur', 'change'] }],
        sequenceTime: [{ required: false, validator: customValidator, min: 0, max: 0, label: '生成时间', trigger: ['blur', 'change'] }],
        sequenceUser: [{ required: false, validator: customValidator, min: 0, max: 20, label: '生成操作用户ID', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.nameOfPermission = 'sequence'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1])
    //   this.userList = resArray[0]['records']
    // },
    getList() {
      this.listLoading = true
      this.listQuery.sequenceTimeStart = ''
      this.listQuery.sequenceTimeEnd = ''
      if (this.listQuery.sequenceTimeRange) {
        this.listQuery.sequenceTimeStart = this.listQuery.sequenceTimeRange[0]
        this.listQuery.sequenceTimeEnd = this.listQuery.sequenceTimeRange[1]
      }
      doGet(this.svc, '/sequence/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.sequenceTimeStart = ''
      this.listQuery.sequenceTimeEnd = ''
      this.listQuery.sequenceTimeRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/sequence/export', this.listQuery)
    },
    handleDelete(row) {
      this.$confirm('您确定删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        doDelete(this.svc, '/sequence/' + row.id, {}).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogVisible = false
        })
      }).catch(e => {
        console.error(e)
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(this.svc, '/sequence/modify', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogVisible = false
        })
      } else if (this.dialogType === 'add') {
        doPost(this.svc, '/sequence/add', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogVisible = false
        })
      }
    },
  }
}
</script>
